package com.cci.kangdao.service.impl;

import com.cci.kangdao.azureBlob.AzureBlobTool;
import com.cci.kangdao.dao.ActivityDao;
import com.cci.kangdao.service.ActivityService;
import com.cci.kangdao.service.PropertiesUtils;
import com.cci.kangdao.utilTool.Upload_Util;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@Service("ActivityService")
public class ActivityServiceImpl implements ActivityService {

	private Logger log = Logger.getLogger(this.getClass().getName());
	
	@Autowired
	private ActivityDao activityDao;
	
	@Autowired
	private PropertiesUtils propertiesUtils;
	
	@Override
	public void addRecord(Map<String, Object> map) {
		HttpServletRequest request = (HttpServletRequest)map.get("request");
		
		int rCount = activityDao.addRecord(map);
		
		if(rCount == 0 ) {
			log.error("下载记录插入异常: " + map.toString());
			return;
		}
		
		// 获取上传图片并存储
		String basePath = request.getSession().getServletContext().getRealPath(propertiesUtils.getPropertiesValue("upload").trim());
		File imgFile = new File(basePath);
		if(!imgFile.exists()){
			imgFile.mkdirs();
		}
		imgFile = null;
		map.put("basePath", basePath);

		// 获取上传文件列表
		List<String> fileList = Upload_Util.uploadMultiData(map);
		
		if(CollectionUtils.isNotEmpty(fileList)) {
			for(String fileName: fileList) {
				
				if(StringUtils.isBlank(fileName)) {
					continue;
				}
				
				//存储上传文件并保存入库
				String filePath = basePath + File.separator + fileName;
				fileName = AzureBlobTool.uploadBlob(propertiesUtils.getPropertiesValue("accountName").trim(),
						propertiesUtils.getPropertiesValue("blobConnection").trim(),
						propertiesUtils.getPropertiesValue("containerName").trim(),
						filePath);
				
				map.put("PicLink", fileName);
				map.put("Remark", "");
				if (StringUtils.isNotEmpty(fileName)) {
					try {
						// 删除服务器文件
						FileUtils.forceDelete(new File(filePath));
					} catch (IOException e) {
						log.warn("删除服务器照片失败" + e.getMessage(), e);
					}
				}
				int pCount = activityDao.addPicture(map);
				
				if(pCount == 0) {
					log.error("文件上传异常: " + fileName + ", 相关记录：" + map.toString());
				}
				
			}
		}
	}

}
